package com.erp.module.zhuanMaiDianTu

import android.app.Activity
import androidx.appcompat.app.AlertDialog
import android.content.Intent
import android.provider.MediaStore
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.RelativeLayout
import androidx.recyclerview.widget.GridLayoutManager
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.activity.BaseActivity
import com.erp.bean.PhotoBean
import com.erp.bean.ZhuanMaiDianBean
import com.erp.bean.zhuanmaidianTuBean
import com.erp.mclass.UnCeHandler
import com.erp.myAdapter.zhuanmaidianTuXxAdapter
import com.erp.util.JsonUtil
import com.erp.util.Myutil
import kotlinx.android.synthetic.main.activity_zhuanmaidiantu.*
import kotlinx.android.synthetic.main.header_knoya.*
import kotlinx.android.synthetic.main.pop_address_picker.view.*
import org.json.JSONException
import org.json.JSONObject


class ZhuanmaidiantuActivity: BaseActivity(),ZhuanMaiDianTuContract.ZhuanMaiDianXXV, View.OnClickListener {
    private var oid =""
    var onum = ""
    lateinit var adapter : zhuanmaidianTuXxAdapter
    lateinit var mBean : zhuanmaidianTuBean
    lateinit var deletephoto : MutableList<PhotoBean>
    lateinit var updatedialog: AlertDialog
    var code = 0
    private val a = "DanjuWTActivity"
    var model = ZhuanMaiDianTuModel()
    override fun getLayoutId(): Int {
        var activityname = a
        return R.layout.activity_zhuanmaidiantu
    }
    override fun initCreate() {
        deletephoto = ArrayList()
        iv_header_left.visibility = View.VISIBLE
        oid = intent.getStringExtra("oid")
        tv_header_title.text = "专卖店安装"
        mBean = zhuanmaidianTuBean()
        mBean.id = oid
        val layoutManager = GridLayoutManager(this, 3)
        adapter = zhuanmaidianTuXxAdapter(this,mBean.listphoto,this)
        GvZhuanMaidian.setLayoutManager(layoutManager)
        GvZhuanMaidian.adapter = adapter

        iv_header_left.setOnClickListener(this)
        tv_header_right.setOnClickListener(this)
        BtAnZhuangShangChuan.setOnClickListener(this)
        TvAddr.setOnClickListener(this)
        getHttpPhoto()
    }

    override fun onClick(v: View?) {
        when (v) {
            iv_header_left -> finish()
            tv_header_right -> {

            }
            BtAnZhuangShangChuan -> {
                updatedialog = Myutil.showupdatedialog(this, "正在上传安装数据", false)
                mBean.tel = EtTel.text.toString()
                mBean.addr = EtXiangXiAddr.text.toString()
                model.setZhuanMaiDian(this,mBean,deletephoto,object : OnUserDataInterface{
                    override fun onUserData(data: String?) {
                        if(data == null){
                            Myutil.MyTost("上传失败")
                            updatedialog.dismiss()
                            return
                        }
                        Myutil.MyTost("上传成功")
                        updatedialog.dismiss()
                        jsondata(data)
                        adapter.notifyDataSetChanged()
                        TvAddr.text = mBean.province+" "+mBean.city+" "+mBean.county+" "+mBean.street
                        Myutil.setet(mBean.tel,EtTel)
                        Myutil.setet(mBean.addr,EtXiangXiAddr)
                    }

                    override fun onNot(throwable: String?) {
                        Log.d("getHttpClient","error"+throwable)
                        Myutil.MyTost("上传失败")
                        updatedialog.dismiss()
                    }

                })
            }
            TvAddr -> {
                val popupWindow = PopupWindow(this)
                val rootView = LayoutInflater.from(this).inflate(R.layout.pop_address_picker, null, false)
                rootView.apvAddress.setOnAddressPickerSure { address, provinceCode, cityCode, districtCode ->
                    TvAddr.text = address
                    mBean.province=provinceCode
                    mBean.city=cityCode
                    mBean.county=districtCode
                    mBean.street=""
                    popupWindow.dismiss()
                }
                rootView.apvAddress.dizhiData();
                popupWindow.contentView = rootView
                popupWindow.isFocusable = true
                popupWindow.isOutsideTouchable = true
                val params = rootView.apvAddress.layoutParams as RelativeLayout.LayoutParams
                params.height = sp.getInt("height",0)/2//设置当前控件布局的高度
                rootView.apvAddress.layoutParams = params//将设置好的布局参数应用到控件中
                popupWindow.animationStyle = R.style.showPopupAnimation
                popupWindow.width = ViewGroup.LayoutParams.MATCH_PARENT
                popupWindow.height = sp.getInt("height",0)*5/10
                popupWindow.showAtLocation(TvAddr, Gravity.BOTTOM, 0, 0)
            }
        }
    }

    fun getHttpPhoto() {
        updatedialog = Myutil.showupdatedialog(this@ZhuanmaidiantuActivity, "获取安装信息", false)
        model.zhuanMaiDian(this, oid, object : OnUserDataInterface {
            override fun onUserData(data: String) {
                Log.d("getHttpClient","date"+data)
                updatedialog.dismiss()
                jsondata(data)
                adapter.notifyDataSetChanged()
                TvAddr.text = mBean.province+" "+mBean.city+" "+mBean.county+" "+mBean.street
                Myutil.setet(mBean.tel,EtTel)
                Myutil.setet(mBean.addr,EtXiangXiAddr)
            }

            override fun onNot(throwable: String) {
                Log.d("getHttpClient","error"+throwable)
                updatedialog.dismiss()
            }
        })
    }
    /**
     * 解析数据
     */
    private fun  jsondata(data: String) {
        Myutil.longlogshow("getHttpClient","data="+data)
        try {
            val jo = JSONObject(data)
            mBean.tel = JsonUtil.getvolue(jo, "tel")
            mBean.province = JsonUtil.getvolue(jo, "province")
            mBean.city = JsonUtil.getvolue(jo, "city")
            mBean.county = JsonUtil.getvolue(jo, "county")
            mBean.street = JsonUtil.getvolue(jo, "street")
            mBean.addr = JsonUtil.getvolue(jo, "addr")
            mBean.listphoto.clear()
            val jo1 = JsonUtil.getjovolue(jo, "kerp")
            val js = JsonUtil.getjsvolue(jo1, "anzhuang_attachment")
            if (js != null) {
                for (i in 0 until js.length()) {
                    val jo1 = js.get(i) as JSONObject
                    if (jo1.getString("filemime").indexOf("image") != -1) {
                        val bean = PhotoBean()
                        bean.fid = JsonUtil.getvolue(jo1, "fid")
                        bean.uri = JsonUtil.getvolue(jo1, "uri")
                        bean.filename = JsonUtil.getvolue(jo1, "filename")
                        bean.timestamp = JsonUtil.getvolue(jo1, "timestamp")
                        bean.filemime = JsonUtil.getvolue(jo1, "filemime")
                        mBean.listphoto.add(bean)
                    }
                }
            }

        } catch (e: JSONException) {
            e.printStackTrace()
        }

    }

    override fun delete(position: Int) {
        val dialog = AlertDialog.Builder(this)
        dialog.setTitle("提示")
        dialog.setMessage("确定要删除这个照片")
        dialog.setPositiveButton("确定") { dialog, which ->
            deletephoto.add(mBean.listphoto[position])
            mBean.listphoto.remove(mBean.listphoto[position])
            adapter.notifyDataSetChanged()
        }
        dialog.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
        dialog.show()
    }

//    override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean {
//        if(position < AnZhuangBean.listphoto.size){
//            val quitdialog = AlertDialog.Builder(this@XianchangPaizhaoActivity).create()
//            quitdialog.show()
//            quitdialog.window!!.setContentView(R.layout.dialog_photo_long)
//            quitdialog.tv_title.text = "确定要删除这张图片吗？"
//            quitdialog.setCanceledOnTouchOutside(false)
//            quitdialog.tv_quite_cancel.setOnClickListener { quitdialog.dismiss() }
//            quitdialog.tv_quite_confirm.setOnClickListener {
//                if(AnZhuangBean.listphoto[position].fid != ""){
//                    updatedialog = Myutil.showupdatedialog(this@XianchangPaizhaoActivity, "正在删除照片", false)
//                    model.deleteAnZhuang(this@XianchangPaizhaoActivity,oid,AnZhuangBean.listphoto[position],object : OnUserDataInterface{
//                        override fun onUserData(data: String?) {
//                            if(data == null){
//                                Myutil.MyTost("删除失败")
//                                updatedialog.dismiss()
//                                return
//                            }
//                            Myutil.MyTost("删除照片成功")
//                            updatedialog.dismiss()
//                            jsondata(data)
//                            adapter.Allnotify(AnZhuangBean.listphoto)
//                            Myutil.setet(AnZhuangBean.isl_asp,EtIslAsp)
//                            Log.d("AnZhuangBean","AnZhuangBean="+AnZhuangBean.toString())
//                        }
//
//                        override fun onNot(throwable: String?) {
//                            Log.d("getHttpClient","error"+throwable)
//                            Myutil.MyTost("删除失败")
//                            updatedialog.dismiss()
//                        }
//
//                    })
//
//                }
//                else{
//                    AnZhuangBean.listphoto.removeAt(position)
//                    adapter.notifyDataSetChanged()
//                }
//                quitdialog.dismiss()
//            }
//        }
//        return true
//    }

//    override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
//        if(position < AnZhuangBean.listphoto.size) {
//            val intent = Intent(this@XianchangPaizhaoActivity, DanjianivActivity::class.java)
//            intent.putExtra("url", AnZhuangBean.listphoto[position].uri)
//            startActivity(intent)
//        }else if(position == AnZhuangBean.listphoto.size){
//            Myutil.photo(this@XianchangPaizhaoActivity, null, 1)
//        }
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        UnCeHandler.buzhou="onActivityResult"
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                99 -> {
                    val selectedImage = data.data
                    val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
                    val c = selectedImage?.let { contentResolver.query(it, filePathColumns, null, null, null) }
                    c!!.moveToFirst()
                    val columnIndex = c.getColumnIndex(filePathColumns[0])
                    val imagePath = c.getString(columnIndex)
                    addphoto(imagePath)
                }
                100 -> {
                    val name = data.getStringExtra("dir")
                    addphoto(name)
                }
            }
        }
    }

    private fun addphoto(name: String) {
        UnCeHandler.buzhou="addphoto"
        val photo = PhotoBean()
        photo.uri = name
        mBean.listphoto.add(photo)
        adapter.notifyDataSetChanged()
    }

}
